package com.jeesite.modules.dp.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.modules.config.RequestInteceptor;
import com.jeesite.modules.dp.service.chatai.DpChartAiUsageLogService;
import com.jeesite.modules.utils.NVL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.utils.StringUtils;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.dp.entity.chatai.DpChatai;
import com.jeesite.modules.dp.entity.kecheng.DpKecheng;
import com.jeesite.modules.dp.entity.order.DpOrder;
import com.jeesite.modules.dp.entity.orderdetail.DpOrderdetail;
import com.jeesite.modules.dp.entity.usercart.DpUsercart;
import com.jeesite.modules.dp.entity.vipinfo.DpVipinfo;
import com.jeesite.modules.dp.entity.xinwen.DpXinwen;
import com.jeesite.modules.dp.entity.yqrecord.DpYqrecord;
import com.jeesite.modules.dp.service.chatai.DpChataiService;
import com.jeesite.modules.dp.service.kecheng.DpKechengService;
import com.jeesite.modules.dp.service.order.DpOrderService;
import com.jeesite.modules.dp.service.orderdetail.DpOrderdetailService;
import com.jeesite.modules.dp.service.usercart.DpUsercartService;
import com.jeesite.modules.dp.service.vipinfo.DpVipinfoService;
import com.jeesite.modules.dp.service.xinwen.DpXinwenService;
import com.jeesite.modules.dp.service.yqrecord.DpYqrecordService;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.wxpay.WxPayConfiguration;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Controller
@Api(tags = "DPBaseApi - 外部用户基础功能api")
@RequestMapping(value = "${adminPath}/dpbaseapi")
@ConditionalOnProperty(name = {"user.enabled", "web.core.enabled"}, havingValue = "true", matchIfMissing = true)
public class DpBaseApiController extends BaseController {

    @Autowired
    private DpOrderService dpOrderService;

    @Autowired
    private DpKechengService dpKechengService;

    @Autowired
    private DpXinwenService dpXinwenService;

    @Autowired
    private DpVipinfoService dpVipinfoService;

    @Autowired
    private DpOrderdetailService dpOrderdetailService;

    @Autowired
    private DpYqrecordService dpYqrecordService;

    @Autowired
    private DpUsercartService dpUsercartService;

    @Autowired
    private UserService userService;

    @Autowired
    private DpChataiService dpChataiService;

    private WxPayService wxPayService;

    @Autowired
    private DpChartAiUsageLogService chartAiUsageLogService;

    @RequestMapping(value = "ailist")
    @ResponseBody
    public Map<String, Object> aiinfolist() {

        Map<String, Object> rs = new HashMap<String, Object>();

        DpChatai ai = new DpChatai();
        ai.setAistatus("1");
        List<DpChatai> list = dpChataiService.findList(ai);
        int usageNum = chartAiUsageLogService.getUsageNum();
        User u = userService.getByLoginCode(UserUtils.getUser());
        rs.put("list", list);
        rs.put("aicount", u.getExtend().getExtendI1());
        rs.put("usagecount", usageNum);
        rs.put("freecount", Integer.parseInt(NVL.emptyVl(Global.getConfig("CHART_AI_DAYFREE_NUM"), "0")));
        rs.put("huihuaid", u.getExtend().getExtendS2() == null ? "" : u.getExtend().getExtendS2());
        return rs;
    }

    @RequestMapping(value = "updateHuihuaid")
    @ResponseBody
    public String updateHuihuaid(String huihuaid) {
        String logincode = UserUtils.getUser().getLoginCode();
        dpChataiService.updateAiHuihuaid(huihuaid, logincode);
        return renderResult(Global.TRUE, "更新成功");
    }

    @RequestMapping(value = "jianAicount")
    @ResponseBody
    public String jianAicount() {
        String logincode = UserUtils.getUser().getLoginCode();
        // 记录当天使用次数
        chartAiUsageLogService.increase();
        // 当天已使用聊天次数
        int usageNum = chartAiUsageLogService.getUsageNum();
        // 每天免费次数
        int freeNum = Integer.parseInt(NVL.emptyVl(Global.getConfig("CHART_AI_DAYFREE_NUM"), "0"));
        if (usageNum > freeNum) {
            // 免费次数使用完，则扣减账户的次数
            dpChataiService.jianAicount(logincode);
        }
        return renderResult(Global.TRUE, "操作成功");
    }

    /**
     * vip会员配置集合
     *
     * @return
     */
    @RequestMapping(value = "viplist")
    @ResponseBody
    public Map<String, Object> viplist() {

        Map<String, Object> rs = new HashMap<String, Object>();
        List<DpVipinfo> list = dpVipinfoService.findList(new DpVipinfo());

        int max = 0;
        for (DpVipinfo info : list) {
            String qyString = info.getVipcontent();
            List<String> qylist = new ArrayList<String>();
            if (StringUtils.isEmpty(qyString)) {
                info.setQylist(qylist);
            } else {
                String[] tmp = qyString.split("\n");
                info.setQylist(Arrays.asList(tmp));

                if (max < tmp.length) {
                    max = tmp.length;
                }
            }

        }

        rs.put("list", list);
        rs.put("maxrow", max + 1);
        return rs;
    }

    /**
     * 会员日期生成
     *
     * @return
     */
    @RequestMapping(value = "memberinfo")
    @ResponseBody
    public Map<String, Object> memberinfo() {
        Map<String, Object> rs = new HashMap<String, Object>();

        String memberinfo = "";
        String buttontext = "";

        User user = userService.getByLoginCode(UserUtils.getUser());
        // 获取会员到期日
        Date userMemberExpireDate = user.getExtend().getExtendD1();
        String userMemberExpireDateStr = userMemberExpireDate == null ? ""
                : DateUtils.formatDateTime(userMemberExpireDate);

        Date today = new Date(System.currentTimeMillis());
        if (userMemberExpireDate == null ||
                "2000-01-01 00:00:00".equals(userMemberExpireDateStr)) {
            // 相等，不是会员
            memberinfo = "您还未成为会员";
            buttontext = "购买会员";
        } else if (userMemberExpireDate.compareTo(today) < 0) {
            // 会员已到期
            memberinfo = "您的会员已于" + userMemberExpireDateStr + "到期";
            buttontext = "购买会员";
        } else if (userMemberExpireDate.compareTo(today) > 0) {
            // 剩余多少天要计算
            memberinfo = DateUtils.formatDate(userMemberExpireDate, "yyyy/MM/dd") + " 到期";
            buttontext = "续期";
        }
        // 2个字符比较
        rs.put("memberinfo", memberinfo);
        rs.put("buttontext", buttontext);
        rs.put("qyjmoney", user.getExtend().getExtendF1());
        rs.put("yqmemberdesc", "邀请好友注册后，您最近3笔订单可享受10%的金额返还");
        rs.put("amount", String.format("%.2f", user.getExtend().getExtendF1()));
        return rs;
    }

    /**
     * 预下单接口，不入数据库
     *
     * @return
     */
    @RequestMapping(value = "precreateOrder")
    @ResponseBody
    public DpOrder precreateOrder(DpOrder order) {

        // 商品总价
        double allmoney = 0;

        // 查询用户账户剩余权益金
        for (DpOrderdetail detail : order.getOrderdetails()) {
            // 查询商品
            if ("1".equals(detail.getOrdertype())) {
                // 查会员信息表
                DpVipinfo info = dpVipinfoService.get(detail.getTypeid());
                allmoney += info.getPrice() * detail.getShuliang();
                detail.setDanjia(info.getPrice());
                detail.setTitle(info.getTitle());
                order.setOrdertype("1");
            }
            // 查询商品
            if ("2".equals(detail.getOrdertype())) {
                // 查课程表
                // 查会员信息表
                DpKecheng info = dpKechengService.get(detail.getTypeid());
                allmoney += info.getPrice() * detail.getShuliang();
                detail.setDanjia(info.getPrice());
                detail.setTitle(info.getKctitle());
                detail.setSmallpic(info.getKcimg());
                order.setOrdertype("2");
            }
            // 查询商品
            if ("3".equals(detail.getOrdertype())) {
                // 查扣子聊天包
                DpChatai ai = dpChataiService.get(detail.getTypeid());
                allmoney += ai.getJiage() * detail.getShuliang();
                detail.setDanjia(ai.getJiage());
                detail.setTitle(ai.getTitle());
                // detail.setSmallpic(info.getKcimg());
                order.setOrdertype("3");

            }

        }

        // 查询用户剩余数量
        User user = userService.getByLoginCode(UserUtils.getUser());
        double qyjmoney = user.getExtend().getExtendF1();

        order.setQyjmoney(qyjmoney);
        order.setJinger(allmoney);
        return order;
    }

    /**
     * 订单下单接口 返回数据库
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "createOrder")
    @ResponseBody
    public DpOrder createOrder(DpOrder order) {

        order.setIsNewRecord(true);

        if (order.getOrderdetails() == null || order.getOrderdetails().isEmpty()) {
            order.setCreateok("0");
            order.setCreateerrmsg("无订单商品明细");
            return order;
        }
        return dpOrderService.saveThenReturn(order);
    }

    @ApiOperation(value = "查询订单")
    @RequestMapping(value = "queryOrder")
    @ResponseBody
    public WxPayOrderQueryResult queryOrder(String outOrderId) throws WxPayException {

        if (wxPayService == null) {
            wxPayService = WxPayConfiguration.wxService();
        }

        return this.wxPayService.queryOrder(null, outOrderId);
    }

    /**
     * @param activeKey 1所有课程，状态为发布，2我的课程，3即将发布
     */
    @RequestMapping(value = "kclistapi")
    @ResponseBody
    public Page<DpKecheng> kclistapi(String activeKey, DpKecheng dpKecheng, HttpServletRequest request,
                                     HttpServletResponse response) {
        dpKecheng.setUno(UserUtils.getUser().getLoginCode());
        if ("2".equals(activeKey)) {
            dpKecheng.setOnlyself("1");
            dpKecheng.setPage(new Page<>(request, response));
            return dpKechengService.frontfindPage(dpKecheng.getPage(), dpKecheng);
        }

        // kcstatus 草稿(0) 正式售卖(1) 即将上架: 2
        if ("1".equals(activeKey)) {
            dpKecheng.setKcstatus("1");
        } else {
            dpKecheng.setKcstatus("2");
        }
        dpKecheng.setPage(new Page<>(request, response));
        return dpKechengService.frontfindPage(dpKecheng.getPage(), dpKecheng);
    }

    @RequestMapping(value = "newslistapi")
    @ResponseBody
    public Page<DpXinwen> newslistapi(DpXinwen dpXinwen, HttpServletRequest request, HttpServletResponse response) {
        dpXinwen.setPage(new Page<>(request, response));
        Page<DpXinwen> page = dpXinwenService.findPage(dpXinwen);
        return page;
    }

    @RequestMapping(value = "qyjlistapi")
    @ResponseBody
    public Page<DpYqrecord> qyjlistapi(DpYqrecord dpYqrecord, HttpServletRequest request,
                                       HttpServletResponse response) {
        dpYqrecord.setPage(new Page<>(request, response));
        return dpYqrecordService.frontfindPage(dpYqrecord.getPage(), UserUtils.getUser().getLoginCode(), dpYqrecord.getQyjtype());
    }

    @RequestMapping(value = "userorderlistapi")
    @ResponseBody
    public Page<DpOrder> userorderlistapi(DpOrder dpOrder, HttpServletRequest request, HttpServletResponse response) {
        dpOrder.setPage(new Page<>(request, response));
        dpOrder.setUserno(UserUtils.getUser().getLoginCode());
        return dpOrderService.findPage(dpOrder);
    }

    @RequestMapping(value = "addusercart")
    @ResponseBody
    public String addusercart(DpUsercart dpUsercart, HttpServletRequest request, HttpServletResponse response) {

        // 此处要判断是否已经加入购物车，暂未实现
        DpUsercart select = new DpUsercart();
        select.setKcid(dpUsercart.getKcid());
        select.setUserno(UserUtils.getUser().getLoginCode());

        long count = dpUsercartService.findCount(select);
        if (count > 0) {
            return renderResult(Global.TRUE, "添加成功");
        }

        dpUsercart.setIsNewRecord(true);
        dpUsercart.setUserno(UserUtils.getUser().getLoginCode());
        // 查询课程id
        DpKecheng dpKecheng = dpKechengService.get(dpUsercart.getKcid());
        dpUsercart.setKctitle(dpKecheng.getKctitle());
        dpUsercart.setKcimg(dpKecheng.getKcimg());
        dpUsercart.setCartprice(dpKecheng.getPrice());

        dpUsercartService.save(dpUsercart);

        return renderResult(Global.TRUE, "保存成功");
    }

    @RequestMapping(value = "getUserCartList")
    @ResponseBody
    public List<DpUsercart> getUserCartList(DpUsercart dpUsercart, HttpServletRequest request,
                                            HttpServletResponse response) {
        dpUsercart.setUserno(UserUtils.getUser().getLoginCode());

        return dpUsercartService.findList(dpUsercart);
    }

    @RequestMapping(value = "clearallUserCart")
    @ResponseBody
    public String clearallUserCart(HttpServletRequest request, HttpServletResponse response) {
        DpUsercart dpUsercart = new DpUsercart();
        dpUsercart.setUserno(UserUtils.getUser().getLoginCode());
        dpUsercartService.deleteByUserno(dpUsercart);

        return renderResult(Global.TRUE, "保存成功");
    }

    @RequestMapping(value = "removeCartById")
    @ResponseBody
    public String removeCartById(DpUsercart dpUsercart, HttpServletRequest request, HttpServletResponse response) {
        dpUsercartService.delete(dpUsercart);
        return renderResult(Global.TRUE, "保存成功");

    }

    @GetMapping("getUserInfo")
    @ResponseBody
    public User getUserInfo() {
        User entity = UserUtils.getUser();
        if (entity != null) {
            return userService.get(entity);
        }
        return null;
    }

    @Value("${domain.path}")
    private String domain;

    @GetMapping("getDomain")
    @ResponseBody
    public String getDomain() {
        return domain;
    }

    @GetMapping("getDictValue")
    @ResponseBody
    public String getMzDesc(String dictType) {
        return Global.getConfig(dictType);
    }
}
